function readFile(filePath)
    local file = io.open(filePath, "r")
    
    if not file then
        print("can't open file: " .. filePath)
        return nil
    end
    
    local content = file:read("*a")
    file:close()
    return content
end

function directoryExists(dir)
    local ok, err = os.rename(dir, dir)
    if ok then
        return true
    elseif err == "No such file or directory" then
        return false
    else
        print("Error: " .. err)
    end
end

function tryCreateDir(dir)
    local _dir = dir
    if getSysType()=='windows' then
        _dir = pathToWin(dir)
    end

    -- print("mkdir winpath:", pathToWin(_dir))
    
    if directoryExists(_dir) then
        print(_dir .. " exists.")
    else
        print(_dir .. " does not exist.")
        cmd_mk = "mkdir " .. _dir
        print(cmd_mk)
        os.execute(cmd_mk)
    end
end

function pathToWin(unixPath)
    local windowsPath = string.gsub(unixPath, '/', '\\')
    return windowsPath
end

function fileExists(filename)
    local file = io.open(filename, "r")
    if file then
      io.close(file)
      return true
    else
      return false
    end
end

function listDir(dir)
    _dir = dir
    if getSysType()=='windows' then
        _dir = pathToWin(_dir)
    end
    cmd = 'dir /b /s '.._dir
    -- print('listDir', cmd)
    local handle = io.popen(cmd)
    local files = {}
    for file in handle:lines() do
        files[#files + 1] = file
    end
    handle:close() 
    return files
end


function extractFile(tgzFilePath, outputDirectory)
    print('extractFile', tgzFilePath, outputDirectory)
    tool_path = 'd:\\apps\\lua54\\'
    tool_7za = tool_path .. "7za"
    print("7za path", tool_7za)

    local check7za = os.execute(tool_7za .. " > nul")
    print('check7za ', check7za)

    if not check7za then
        return "Error: 7-Zip is not installed or not accessible."
    end

    local command = string.format(tool_path .. '7za x "%s" -o"%s" -y', tgzFilePath, outputDirectory)

    print('extract command', command)
    
    local status, codeOrReason = os.execute(command)
    print('extract status', status)

    if status then
        if codeOrReason then
            return "Success: The file has been extracted to " .. outputDirectory .. "."
        else
            return "Error: An error occurred with exit code " .. codeOrReason .. "."
        end
    else
        return "Error: Failed to execute 7-Zip command."
    end
end
